package com.example.sunmiv1.utils.imgutils;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2019-01-24 18:27.
 */

//上傳所用的任務類
public class UploadImg {
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 1000;   //超時時間
    private static final String CHARSET = "utf-8"; //設置編碼

    /**
     * android上傳文件到服務器
     *
     * @param file       需要上傳的文件
     * @param RequestURL 請求的rul
     * @return 返回響應的內容
     */
    public static String uploadFile(File file, String RequestURL, JSONObject jsonObject) {
        String result = null;
        String BOUNDARY = UUID.randomUUID().toString();  //邊界標識   隨機生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data";   //內容類型

        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true);  //允許輸入流
            conn.setDoOutput(true); //允許輸出流
            conn.setUseCaches(false);  //不允許使用緩存
            conn.setRequestMethod("POST");  //請求方式
            conn.setRequestProperty("Charset", CHARSET);  //設置編碼
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            conn.setRequestProperty("action", "upload");
            conn.connect();

            if (file != null) {
                /**
                 * 當文件不爲空，把文件包裝並且上傳
                 */
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                StringBuffer sb = new StringBuffer();
                // 首先組拼文本類型的參數
                Iterator<String> keys = jsonObject.keys();
                while (keys.hasNext()) {
                    String key = String.valueOf(keys.next());
                    try {
                        String value = jsonObject.get(key).toString();
                        sb.append(PREFIX);
                        sb.append(BOUNDARY);
                        sb.append(LINE_END);
                        sb.append("Content-Disposition: form-data; name=\""
                                + key + "\"" + LINE_END);
                        sb.append("Content-Type: text/plain; charset=" + CHARSET + LINE_END);
                        sb.append("Content-Transfer-Encoding: 8bit" + LINE_END);
                        sb.append(LINE_END);
                        sb.append(value);
                        sb.append(LINE_END);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 這裏重點注意：
                 * name裏面的值爲服務器端需要key   只有這個key 纔可以得到對應的文件
                 * filename是文件的名字，包含後綴名的   比如:abc.png
                 */
                Log.e(TAG, "uploadFile: 文件名稱==" + file.getName());
                sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 獲取響應碼  200=成功
                 * 當響應成功，獲取響應的流
                 */
                int res = conn.getResponseCode();
                if (res == 200) {
                    InputStream input = conn.getInputStream();
                    StringBuffer sb1 = new StringBuffer();
                    int ss;
                    while ((ss = input.read()) != -1) {
                        sb1.append((char) ss);
                    }
                    result = sb1.toString();
                    Log.e(TAG, "uploadFile: ===" + result);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
